//
//  LostCarAlarmViewController.m
//  LocomotiveGuards
//
//  Created by xys on 15/11/30.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "LostCarAlarmViewController.h"
#import "Masonry.h"
#import "LostCarAlarmView.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#import "SearchAreas.h"

typedef NS_ENUM(NSInteger, LostCarAlarmPickerViewType)
{
    LostCarAlarmPickerViewTypeDate       = 0, //日期
    LostCarAlarmPickerViewTypeTime       = 1, //时间
    LostCarAlarmPickerViewAddress        = 2, //地址
};

@interface LostCarAlarmViewController ()<LostCarAlarmViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
    NSString * districtStr;
    UIView * grayView;
    NSDictionary *_listDic;
}
@property (nonatomic,strong) LostCarAlarmView * scrollView;
@property (nonatomic,strong) UIDatePicker * dateAndTimePicker;
@property (nonatomic,strong) UIView * addressPickView;
@property (nonatomic,strong) NSArray * subLocalityList;
@property (nonatomic,strong) UIView * dateAndTimeView;
@end

@implementation LostCarAlarmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.rightbtn removeFromSuperview];
    [self.centerbtn setImage:nil forState:UIControlStateNormal];
    [self.centerbtn setTitle:@"丢车报警" forState:UIControlStateNormal];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.leftbtn addTarget:self action:@selector(goBackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    self.scrollView = [[LostCarAlarmView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navbackview.frame), SCREEN_WIDTH, SCREEN_HEIGHT-CGRectGetHeight(self.navbackview.frame)-CGRectGetHeight(self.tabBarController.tabBar.frame))];
    self.scrollView.lostCarAlarmDelegate = self;
    self.scrollView.contentSize = self.scrollView.mContentSize;
    [_scrollView setScrollEnabled:YES];
    [self.view addSubview:self.scrollView];
    
    [self getEbicycleInfo];
    [self getUserInfo];
}

/**
 *  解决IOS7以下系统 UIScrollView不能滚动的问题
 */
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = self.scrollView.mContentSize;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - LostCarAlarmViewDelegate method -

- (void)dateButtonClicked:(UIButton *) _btn
{
    if (self.dateAndTimeView)
    {
        [self.dateAndTimeView removeFromSuperview];
        self.dateAndTimeView = nil;
    }
    self.dateAndTimeView = [self allocDatePicker:LostCarAlarmPickerViewTypeDate];
    [self.view addSubview:self.dateAndTimeView];
}

- (void)timeButtonClicked:(UIButton *) _btn
{
    if (self.dateAndTimeView)
    {
        [self.dateAndTimeView removeFromSuperview];
        self.dateAndTimeView = nil;
    }
    self.dateAndTimeView = [self allocDatePicker:LostCarAlarmPickerViewTypeTime];
    [self.view addSubview:self.dateAndTimeView];
}

/**
 *  选择区
 *
 *  @param _province 所在省
 *  @param _city     所在市
 */
- (void)selectSubLocalityButtonClicked:(NSString *) _province city:(NSString *) _city
{
    if (self.addressPickView)
    {
        [self.addressPickView removeFromSuperview];
        self.addressPickView = nil;
    }
    //self.subLocalityList = @[@"北京",@"南京",@"天津",@"上海",@"苏州",@"adf",@"adsfas"];
    SearchAreas * searchAreas = [[SearchAreas alloc]init];
    self.subLocalityList = [searchAreas returnDistrictsWithProvince:_province City:_city];
    self.addressPickView = [self allocUIPickerView];
    
        
    [self.addressPickView.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         UIView * view = obj;
         if ([view isKindOfClass:[UIPickerView class]])
         {
             [(UIPickerView*)view reloadAllComponents];
             *stop = YES;
         }
     }];
}

/**
 *  丢车报警
 *
 *  @param _paramaDict 请求参数
 */
- (void)reportLost:(NSDictionary *)_paramaDict
{
    if (!_paramaDict)
    {
        return;
    }
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    [loadmsg delayLoadImages];
    NSString * urlMethod = [NSString stringWithFormat:@"%@reportLost.do",urlstring];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:urlMethod withParam: _paramaDict success:
     ^(AFHTTPRequestOperation *operation, id responseObject)
    {
        [loadmsg delayImagesRemove];
         NSDictionary * responseDict = responseObject;
         NSNumber * flag = [responseDict objectForKey:@"flag"];
         //self.scrollView.userInteractionEnabled = NO;
         if (flag.longValue == 0 )
         {
             //报警成功然后切换到报警备案界面
             [self.navigationController popViewControllerAnimated:YES];
             [[NSNotificationCenter defaultCenter]postNotificationName:@"LostCarSuccessNotification" object:nil];
             [self getPrivacyRequest];
         }
         else
         {
             NSLog(@"丢车报警失败");
             [PopMsg showMessage:responseObject[@"msg"] Lasttime:1.0];
         }
        
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [loadmsg delayImagesRemove];
         [PopMsg showMessage:@"网络连接失败!" Lasttime:1.0];
     }];

}

//获取隐私信息
- (void)getPrivacyRequest
{
    NSDictionary *paramdic=@{@"bid":[[NSUserDefaults standardUserDefaults] objectForKey:@"bid"]};
    NSString *url = [urlstring stringByAppendingString:@"getPrivacyGuardConfig.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        
        NSDictionary * responseDict = responseObject;
        NSNumber * flag = [responseDict objectForKey:@"flag"];
        if (flag.longValue == 0 )
        {
            _listDic = responseDict;
            [self setPrivacyRequest];
        }
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
    }];
}

//设置隐私信息
- (void)setPrivacyRequest
{
    if ( !_listDic )
    {
        return;
    }
    
    NSDictionary *paramdic = [NSDictionary new];
    
    paramdic=@{@"bid":[[NSUserDefaults standardUserDefaults] objectForKey:@"bid"],
               @"rtFlag":[_listDic objectForKey:@"rtFlag"],
               @"anchorFlag":[_listDic objectForKey:@"anchorFlag"],
               @"trackFlag":@"0"};
    
    NSString *url = [urlstring stringByAppendingString:@"setPrivacyGuardConfig.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success: nil failure:nil];
}

#pragma mark -- UIPickerViewDelegate,UIPickerViewDataSource --

//返回有几列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//返回指定列的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.subLocalityList.count;
}

//返回指定列，行的高度，就是自定义行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return CGRectGetWidth(self.view.frame)*0.5*0.2;
}

//返回指定列的宽度
- (CGFloat) pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    return CGRectGetWidth(self.addressPickView.frame);
}

// 自定义指定列的每行的视图，即指定列的每行的视图行为一致
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (!view){
        view = [[UIView alloc]init];
    }
    UILabel *text = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(pickerView.frame), CGRectGetWidth(self.view.frame)*0.5*0.2)];
    text.backgroundColor = [UIColor whiteColor];
    text.textAlignment = NSTextAlignmentCenter;
    text.text = [self.subLocalityList objectAtIndex:row];
    [view addSubview:text];
    
    return view;
}

//显示的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *str = [self.subLocalityList objectAtIndex:row];
    return str;
}

//显示的标题字体、颜色等属性
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *str = [self.subLocalityList objectAtIndex:row];
    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc]initWithString:str];
    [AttributedString addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18], NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [AttributedString  length])];
    
    return AttributedString;
}

//被选择的行
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"HANG%@",[_subLocalityList objectAtIndex:row]);
    districtStr = [_subLocalityList objectAtIndex:row];
}

#pragma mark - button clicled handler -

/**
 *  日期、时间、地址选择器下面的确定按钮
 *
 *  @param _btn <#_btn description#>
 */
- (void)pickerViewConfirmButtonClicked:(UIButton *) _btn
{
    NSDate * date = self.dateAndTimePicker.date;
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    if (_btn.tag == LostCarAlarmPickerViewTypeDate)
    {
        formatter.dateFormat=@"yyyy.MM.dd";
        NSString *timeStr=[formatter stringFromDate:date];
        [self.scrollView.dateButton setTitle:timeStr forState:UIControlStateNormal];
        [self.dateAndTimeView removeFromSuperview];
        self.dateAndTimeView = nil;
    }
    else if(_btn.tag == LostCarAlarmPickerViewTypeTime )
    {
        formatter.dateFormat=@"HH:mm";
        NSString *timeStr=[formatter stringFromDate:date];
        [self.scrollView.timeButton setTitle:timeStr forState:UIControlStateNormal];
        [self.dateAndTimeView removeFromSuperview];
        self.dateAndTimeView = nil;
    }
    else
    {
        [self.scrollView.districtButton setTitle:districtStr?districtStr:_subLocalityList.firstObject forState:UIControlStateNormal];
        [self.addressPickView removeFromSuperview];
        self.addressPickView  = nil;
        [grayView removeFromSuperview];
        grayView = nil;
    }
}

- (void)cancelButtonClicked:(UIButton *) _cancelButton
{
    if (_cancelButton.tag == LostCarAlarmPickerViewTypeDate)
    {
        [self.dateAndTimeView removeFromSuperview];
        self.dateAndTimeView = nil;
    }
    else if(_cancelButton.tag == LostCarAlarmPickerViewTypeTime )
    {
        [self.dateAndTimeView removeFromSuperview];
        self.dateAndTimeView = nil;
    }
    else
    {
        [self.addressPickView removeFromSuperview];
        self.addressPickView = nil;
        [grayView removeFromSuperview];
        grayView = nil;
    }
}

- (void)goBackButtonClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - custom method - 

- (UIView *) allocDatePicker:(LostCarAlarmPickerViewType) _type
{
    UIView *  dateAndTimeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    dateAndTimeView.backgroundColor = RGBACOLOR(100, 100, 100, 0.5);
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0.1*SCREEN_WIDTH,0.25*SCREEN_HEIGHT, 0.8*SCREEN_WIDTH, 0.5*SCREEN_HEIGHT)];
    backView.backgroundColor = [UIColor whiteColor];
    backView.layer.cornerRadius = 10;
    [dateAndTimeView addSubview:backView];

    UIButton * confirmButton = [[UIButton alloc]init];
    confirmButton.tag = LostCarAlarmPickerViewAddress;
    confirmButton.backgroundColor = [UIColor whiteColor];
    confirmButton.layer.cornerRadius = 10;
    confirmButton.tag = _type;
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:RGBCOLOR(6, 64, 203) forState:UIControlStateNormal];
    [confirmButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [confirmButton addTarget:self action:@selector(pickerViewConfirmButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * cancelButton = [[UIButton alloc]init];
    cancelButton.backgroundColor = [UIColor whiteColor];
    cancelButton.layer.cornerRadius = 10;
    cancelButton.tag = _type;
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:RGBCOLOR(6, 64, 203) forState:UIControlStateNormal];
    [cancelButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [cancelButton addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [backView addSubview:confirmButton];
    [backView addSubview:cancelButton];
    
    [cancelButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(backView.bottom);
        make.height.equalTo(40);
        make.left.equalTo(backView.left);
        make.width.equalTo(CGRectGetWidth(backView.frame)*0.5);
    }];
    
    [confirmButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(cancelButton.bottom);
        make.height.equalTo(cancelButton.height);
        make.right.equalTo(backView.right);
        make.width.equalTo(CGRectGetWidth(backView.frame)*0.5);
    }];
    
    UIView * rowline = [[UIView alloc]init];
    rowline.backgroundColor = [UIColor grayColor];
    [backView addSubview:rowline];
    [rowline makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(1);
        make.bottom.equalTo(confirmButton.top);
        make.left.equalTo(backView.left);
        make.right.equalTo(backView.right);
    }];
    
    UIView * colline = [[UIView alloc]init];
    colline.backgroundColor = [UIColor grayColor];
    [backView addSubview:colline];
    [colline makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(1);
        make.bottom.equalTo(backView.bottom);
        make.top.equalTo(confirmButton.top);
        make.left.equalTo(cancelButton.right);
    }];
    
    self.dateAndTimePicker = [[UIDatePicker alloc]init];
    self.dateAndTimePicker.backgroundColor = [UIColor whiteColor];
    [self.dateAndTimePicker setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    self.dateAndTimePicker.timeZone = [NSTimeZone systemTimeZone];
    NSDate *now = [[NSDate alloc]init];
    [self.dateAndTimePicker setDate:now animated:NO];
    if (_type == LostCarAlarmPickerViewTypeDate)
    {
        self.dateAndTimePicker.datePickerMode = UIDatePickerModeDate;
        self.dateAndTimePicker.tag = LostCarAlarmPickerViewTypeDate;
        self.dateAndTimePicker.maximumDate = self.dateAndTimePicker.date;
        self.dateAndTimePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:-365*24*60*60];
    }
    else
    {
        self.dateAndTimePicker.datePickerMode = UIDatePickerModeTime;
        self.dateAndTimePicker.tag = LostCarAlarmPickerViewTypeTime;
    }
    
    [backView addSubview:self.dateAndTimePicker];
    [self.dateAndTimePicker makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView.top).with.offset(10);
        make.bottom.equalTo(rowline.top);
        make.left.equalTo(backView.left).with.offset(10);
        make.right.equalTo(backView.right).with.offset(-10);
    }];
    return dateAndTimeView;
}

/**
 *  地址选择视图
 *
 *  @return <#return value description#>
 */
- (UIView * )allocUIPickerView
{
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    grayView.backgroundColor = RGBACOLOR(100, 100, 100, 0.5);
    [self.view addSubview:grayView];
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0.1*SCREEN_WIDTH,0.25*SCREEN_HEIGHT, 0.8*SCREEN_WIDTH, 0.5*SCREEN_HEIGHT)];
    backView.backgroundColor = [UIColor whiteColor];
    backView.layer.cornerRadius = 10;
    [self.view addSubview:backView];
    
    UILabel * title = [[UILabel alloc]init];
    [title setFont:[UIFont systemFontOfSize:15]];
    title.textColor = [UIColor blackColor];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"选择区";
    [backView addSubview:title];
    [title makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backView.left).with.offset(20);
        make.right.equalTo(backView.right).with.offset(-20);
        make.top.equalTo(backView.top).with.offset(10);
        make.height.equalTo(25);
    }];
    
    UIButton * confirmButton = [[UIButton alloc]init];
    confirmButton.tag = LostCarAlarmPickerViewAddress;
    confirmButton.backgroundColor = [UIColor whiteColor];
    confirmButton.layer.cornerRadius = 10;
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:RGBCOLOR(6, 64, 203) forState:UIControlStateNormal];
    [confirmButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [confirmButton addTarget:self action:@selector(pickerViewConfirmButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * cancelButton = [[UIButton alloc]init];
    cancelButton.backgroundColor = [UIColor whiteColor];
    cancelButton.layer.cornerRadius = 10;
    cancelButton.tag = LostCarAlarmPickerViewAddress;
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:RGBCOLOR(6, 64, 203) forState:UIControlStateNormal];
    [cancelButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [cancelButton addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [backView addSubview:confirmButton];
    [backView addSubview:cancelButton];
    
    [cancelButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(backView.bottom);
        make.height.equalTo(40);
        make.left.equalTo(backView.left);
        make.width.equalTo(CGRectGetWidth(backView.frame)*0.5);
    }];
    
    [confirmButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(cancelButton.bottom);
        make.height.equalTo(cancelButton.height);
        make.right.equalTo(backView.right);
        make.width.equalTo(CGRectGetWidth(backView.frame)*0.5);
    }];
    
    UIView * rowline = [[UIView alloc]init];
    rowline.backgroundColor = [UIColor grayColor];
    [backView addSubview:rowline];
    [rowline makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(1);
        make.bottom.equalTo(confirmButton.top);
        make.left.equalTo(backView.left);
        make.right.equalTo(backView.right);
    }];
    
    UIView * colline = [[UIView alloc]init];
    colline.backgroundColor = [UIColor grayColor];
    [backView addSubview:colline];
    [colline makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(1);
        make.bottom.equalTo(backView.bottom);
        make.top.equalTo(confirmButton.top);
        make.left.equalTo(cancelButton.right);
    }];
    
    UIPickerView * pickerView = [[UIPickerView alloc]init];
    //pickerView.backgroundColor = [UIColor greenColor];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    [backView addSubview:pickerView];
    [pickerView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backView.left);
        make.top.equalTo(title.bottom);
        make.right.equalTo(backView.right);
        make.bottom.equalTo(rowline.top);
    }];
    
    return backView;

}


/**
 *  查询我的车辆
 */
- (void)getEbicycleInfo
{
    NSString * urlMethod = [NSString stringWithFormat:@"%@getEbicycleInfo.do",urlstring];
    NSString * loginId = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    NSDictionary * paramDict = @{@"loginId":loginId};
    [K_AppDelegate GenerateHTTPRequestWithUrl:urlMethod withParam: paramDict success:
     ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * responseDict = responseObject;
         NSNumber * flag = [responseDict objectForKey:@"flag"];
         if (flag.longValue == 0 )
         {
             NSArray * bicycleLists = [responseDict objectForKey:@"bicycleLists"];
             if ( bicycleLists && bicycleLists.count > 0 )
             {
                /*
                    刷新用户界面信息
                 */
                 self.scrollView.bicycleInfoDict = bicycleLists.firstObject;
             }
         }
         else
         {
            [PopMsg showMessage:@"获取我的车辆信息失败!" Lasttime:1.0];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [PopMsg showMessage:@"网络连接失败!" Lasttime:2.0];
     }];
}

/**
 *  获取用户信息
 */
- (void)getUserInfo
{
    NSString * urlMethod = [NSString stringWithFormat:@"%@getUserInfo.do",urlstring];
    NSString * loginId = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    NSDictionary * paramDict = @{@"loginId":loginId};
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    [loadmsg delayLoadImages];
    [K_AppDelegate GenerateHTTPRequestWithUrl:urlMethod withParam: paramDict success:
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         NSDictionary * responseDict = responseObject;
         NSNumber * flag = [responseDict objectForKey:@"flag"];
         
         if (flag.longValue == 0 )
         {
            /*
                刷新用户界面信息
            */
            self.scrollView.userInfoDict = responseDict;
         }
         else
         {
             [PopMsg showMessage:@"获取用户信息失败!" Lasttime:2.0];
         }
         [loadmsg delayImagesRemove];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [loadmsg delayImagesRemove];
         [PopMsg showMessage:@"网络连接失败!" Lasttime:2.0];
     }];
}

@end
